/******************************************************************************
 * This file is part of libemb.
 *
 * libemb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * libemb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libemb.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project: Embedme
 * Author : FergusZeng
 * Email  : cblock@126.com
 * git	  : https://git.oschina.net/cblock/embedme
 * Copyright 2014~2020 @ ShenZhen ,China
*******************************************************************************/
#include "ArgUtil.h"
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>

using namespace std;

namespace libemb{
ArgOption::ArgOption()
{
}

ArgOption::~ArgOption()
{
}

void ArgOption::addOption(char option,int args)
{
	m_shortOptions.append(1,option);
	m_shortOptionPattern.append(1,option);
	switch(args){
	case 0:		/* 不带参数 */
		break;
	case 1:		/* 带一个参数 */
		m_shortOptionPattern.append(":");
		break;
	default:	/* 可带可不带 */
		m_shortOptionPattern.append("::");
		break;
	}
}

void ArgOption::parseArgs(int argc, char* argv[])
{
	int ret ;
	while(1)
	{
		ret = getopt_long(argc,argv,m_shortOptionPattern.c_str(),NULL,NULL);
		if (ret==-1)
		{
			break;
		}
		for(int i=0; i<m_shortOptions.size(); i++)
		{
			char ch = (char)ret;
			if (m_shortOptions[i]==ch)
			{
				std::string value="";
				std::string option(1,ch);
				if (optarg!=NULL)
				{
					value = std::string(optarg);
				}
				std::pair<std::string,std::string> optionPair(option,value);
				m_optionMap.insert(optionPair);
			}
		}
	}
}

bool ArgOption::getValue(char option, std::string& value)
{
	std::string opt(1,option);
	ArgOptionMap::iterator iter = m_optionMap.find(opt);
	if(iter!=m_optionMap.end())
	{
		value = iter->second;
		return true;
	}
    else
    {
        return false;
    }
}

InputGet::InputGet()
{

}

InputGet::~InputGet()
{

}

void InputGet::waitInput()
{
	 std::cin >> m_inputStr;
}

bool InputGet::match(std::string item)
{
	if (m_inputStr==item)
	{
		return true;
	}
	return false;
}
int InputGet::size()
{
	return m_inputStr.size();
}

int InputGet::toInt()
{
	if (m_inputStr.empty())
	{
		return 0;
	}
	return atoi(m_inputStr.c_str());
}

float InputGet::toFloat()
{
	if (m_inputStr.empty())
	{
		return 0.0;
	}
	return atof(m_inputStr.c_str());
}

std::string InputGet::toString()
{
	return m_inputStr;
}

const char* InputGet::toCString()
{
	return m_inputStr.c_str();
}

}
